<?php
require "../../../../global.php";

/****************正式环境请更换以下信息***********************/
//3DES密钥
$DESkey = '1E5HsITy8EtdcC4LrSDKuFSc';

//3DES向量
$DESiv = '1E5HsITy';

//商户的md5证书
$MD5key = '36451620901856065970269330053246181842887948974683586506701057676567422219322046647065958403072037230625137727476541950060891824';

//商户的RSA公钥
$RSAkey = '<RSAKeyValue><Modulus>yPJGRlr88jmJtR31g4mhwDo3qonw9/mR1cWGeYY/a9bk9MyP1BjTu6QRb96Z+V033HLUngYL+pfqZN9+HPjfI5bMsFwScJ+KKDst88ZWP8bs8OWQ89RKr3Voff922rGE3wGZ4N2ycpnE2p+Z9+2wBQJ2UqVoDmj4dGVS4LnCBQ0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>';

/****************获取表单信息******************************/
//商户号
$pMerCode = $_POST['pMerCode'];

//商户交易订单号
$pBillNo = $_POST['pBillNo'];

//构建特殊的订单形式
if(strstr($pBillNo,",")){
	$pBillNo=str_replace(",", $_REQUEST["pAttachpaty"]."", $pBillNo).$_REQUEST["pAttachpaty"];
}else {
	$pBillNo.=$_REQUEST["pAttachpaty"];
}

$realorderno=$pBillNo;
//商户附加信息 这里是完整的订单信息
$pAttach = $pBillNo."^".$_REQUEST["pAttach"];

//构建映射表,把真实订单号存入数据库里，再生成一个简短的订单号供支付
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select * from ".DQ."onlingpayorder where onlingpayorder2='".$pAttach."'";
$res=$mydb->db_query($sql);
if($rs=$mydb->db_fetch_array($res)){
	$newordern=$rs["onlingpayorder1"];
}
else{
	//生成新的订单号用于向第三方支付
	$newordern="M".date("ydmhis").rand(10, 99);
	$sql="insert into ".DQ."onlingpayorder (onlingpayorder1,onlingpayorder2) value('".$newordern."','".$pAttach."')";
	$mydb->db_query($sql);
}




$pBillNo=$newordern.rand(10, 99);//新生成的16位订单号和最后两位的随机数号


//支付币种
$pCurrency = $_POST['pCurrency'];

//语种
$pLang = $_POST['pLang'];

//订单金额(保留两位小数)
$pAmount = number_format($_POST['pAmount'], 2, '.', '');

//商户录入日期
$pDate = $_POST['pDate'];

//信用卡种类
$pGateWayType = $_POST['pGateWayType'];


//录入返回签名方式
$pRetEncodeType = $_POST['pRetEncodeType'];

//订单有效期 
$pBillEXP = $_POST['pBillEXP'];

//支付结果返回地址 
$pReturnUrl = "http://".$_SERVER['SERVER_NAME']."/Index/Lib/Order/CardOnlineIpsRmb/OrderReturn.php";

//错误返回地址 
$pErrorUrl = "http://".$_SERVER['SERVER_NAME']."/Index/Lib/Order/CardOnlineIpsRmb/OrderReturn.php";

//订单加密方式(pCardInfo的加密方式)
$pOrderEncodeType = $_POST['pOrderEncodeType'];

//支付结果返回方式：0 ( HTTP方式)  
$pResultType = '0';

//访问者权限 
$pAuthority = $_POST['pAuthority'];

//备用 
$pDetails = '';

//商品信息 
$pGoodsInfo = $_POST['pGoodsInfo'];

//是否直连 
$pDirect = $_POST['pDirect'];

//持卡人加密信息
$pCardInfo = '';

//pDirect=1是直连方式,pDirect为空是非直连方式
if ($_POST['pDirect'] == '1')
{
  $pCardInfo = $_POST['pName'] . '|' .
               $_POST['pIDType'] . '|' .
               $_POST['pIDNum'] . '|' .
               $_POST['pTel'] . '|' .
               $_POST['pCardExp'] . '|' .
               $_POST['pCardType'] . '|' .
               $_POST['pCardNum'] . '|' .
               $_POST['pIssueBank'] . '|' .
               $_POST['pIssueCountry'] . '|' .
               $_POST['pCVV'];
}
else
{
  $pCardInfo = $_POST['pName'] . '|' .
               $_POST['pIDType'] . '|' .
               $_POST['pIDNum'] . '|' .
               $_POST['pTel'];
}

//RSA加密
if ($pOrderEncodeType == '1')
{
	require_once('rsa.function.php');

	//读取RSA公钥中的Modulus和Exponent
	$xml = new DOMDocument();
	$xml->loadXML($RSAkey);
	$Modulus = $xml->getElementsByTagName('Modulus')->item(0)->nodeValue;
	$Exponent = $xml->getElementsByTagName('Exponent')->item(0)->nodeValue;
	unset($xml);

	$publicKey = kimssl_pkey_get_public($Modulus, $Exponent);
	openssl_public_encrypt($pCardInfo, $pCardInfo, $publicKey);
	$pCardInfo = base64_encode($pCardInfo);
	openssl_free_key($publicKey);
}

//3DES加密
if ($pOrderEncodeType == '2')
{
	require_once('des.class.php');

	//创建3DES的对象
	$DES = new DES;

	//3DES密钥
	$DES->key = $DESkey;

	//3DES向量
	$DES->iv = $DESiv;

	//调用3DES的加密方法
	$pCardInfo = $DES->DESEncrypt($pCardInfo);
}

//md5的source
$strMd5Temp = $pBillNo . $pMerCode . $pCurrency . $pAmount . $pDate . $MD5key;

//md5的摘要
$pSignMD5 = md5($strMd5Temp);

//提交的信用卡支付网关的url地址(正式环境请更改为：https://gw5.ips.com.cn:444/B2C/AuthTrade/Pay.aspx)
$actionUrl = 'https://gw5.ips.com.cn:444/B2C/AuthTrade/Pay.aspx';



//=======================================初始化梦之旅订单信息
$pBillNoarr=explode(",", $pAttach);
preg_match("/[t|h][\d]{7}j[\d]/", $pAttach,$pBillNoarr);
$pricelist=$_REQUEST["pAttach"];
$alimoneylistarr=explode(",", $pricelist);


$i=0;
$pBillNotemp="";
foreach ($pBillNoarr as $v){
	$sql="select pay1 from ".$SystemConest[7]."pay where pay1='".$v."'";
	$res=$mydb->db_query($sql);
	if($mydb->db_num_rows($res)<1){
		$sql="insert into ".$SystemConest[7]."pay (pay1,pay2,pay3,pay5) value('".$v."',573,".$alimoneylistarr[$i].",'环讯信用卡')";
		$mydb->db_query($sql);
	}
	$i++;
	
}





//pDirect=1采用webservice直连方式处理
if($pDirect == '1')
{
	//参数转为数组形式传递
	$strxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
               <OrderInfo>
                 <pBillNo>{$pBillNo}</pBillNo>
                 <pMerCode>{$pMerCode}</pMerCode>
                 <pCurrency>{$pCurrency}</pCurrency>
                 <pLang>{$pLang}</pLang>
                 <pAmount>{$pAmount}</pAmount>
                 <pDate>{$pDate}</pDate>
                 <pGateWayType>{$pGateWayType}</pGateWayType>
                 <pAttach>{$pAttach}</pAttach>
                 <pRetEncodeType>{$pRetEncodeType}</pRetEncodeType>
                 <pOrderEncodeType>{$pOrderEncodeType}</pOrderEncodeType>
                 <pSignMD5>{$pSignMD5}</pSignMD5>
                 <pBillEXP>{$pBillEXP}</pBillEXP>
                 <pReturnUrl>{$pReturnUrl}</pReturnUrl>
                 <pCardInfo>{$pCardInfo}</pCardInfo>
                 <pResultType>{$pResultType}</pResultType>
                 <pAuthority>{$pAuthority}</pAuthority>
                 <pDetails>{$pDetails}</pDetails>
                 <pGoodsInfo>{$pGoodsInfo}</pGoodsInfo>
               </OrderInfo>";

	if(!extension_loaded('soap'))
	{
		echo '请安装并加载soap扩展!';
		exit;
	}
  
	//调用WebService：正式环境请更改webservice地址为https://gw5.ips.com.cn:444/B2C/AuthTrade/PaymentWService.asmx?WSDL
	$objSoapClient = new SoapClient('http://payAT.ips.com.cn/B2C/AuthTrade/PaymentWService.asmx?WSDL');
	$aryResult = $objSoapClient->SubmitOrder($strxml);

	/**************************WebService返回处理逻辑********************************
	1.判断pSucc
	  若 pSucc 等“S”, 表示录入成功; 若等于“F”, 表示录入失败, 此时无需再进行以下步骤。
	2.数据验证 
	  可以使用IPS 提供的签名验证组件，对返回的关键信息进行验证，以确保订单信息 
	  安全，防止黑客恶意攻击及篡改订单信息。
	3.判断订单号和金额 
	  为安全起见，商户应该将自己系统中存放的订单信息和IPS 返回的订单信息进行比对， 
	  以保证订单数据真实可信。建议比对的项：订单编号和订单金额。 
	4.在成功完成以上步骤后，商户可以根据需要进行其他操作。
	*******************************************************************************/
	if(!extension_loaded('dom'))
	{
		echo '不支持DOM!';
		exit;
	}
	$xml = new DOMDocument();
	$xml->loadXML($aryResult);

	//录入结果: S-录入成功 F-录入失败
	$pSucc = $xml->getElementsByTagName('pSucc')->item(0)->nodeValue;

	//返回信息
	$pMsg = $xml->getElementsByTagName('pMsg')->item(0)->nodeValue;
  
	if($pSucc == 'S')
	{
		//商户订单号
		$pBillNo = $xml->getElementsByTagName('pBillNo')->item(0)->nodeValue;

		//订单金额
		$pAmount = $xml->getElementsByTagName('pAmount')->item(0)->nodeValue;

		//订单日期
		$pDate = $xml->getElementsByTagName('pDate')->item(0)->nodeValue;

		//IPS订单号
		$pIpsBillNo = $xml->getElementsByTagName('pIpsBillNo')->item(0)->nodeValue;

		//币种
		$pCurrency = $xml->getElementsByTagName('pCurrency')->item(0)->nodeValue;
		
		//签名
		$pSignature = $xml->getElementsByTagName('pSignature')->item(0)->nodeValue;

		unset($xml);

		//签名原文:订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种
		$content = $pBillNo . $pAmount . $pDate . $pSucc . $pIpsBillNo . $pCurrency;

		//签名验证是否通过
		$verify = false;

		//md5withrsa的签名验证方式
		if($pRetEncodeType == '11')
		{
			//创建com组件
			$MD5withRSA = new COM('IpsVerify.RSAMd5');
			
			//使用公钥文件的绝对路径
			$result = $MD5withRSA->VerifyMessage("C:\\PubKey\\pub.txt", $content, $pSignature);

			/*******************
			返回代码定义
			0   表示签名验证成功
			-1  表示系统错误
			-2  表示文件绑定错误
			-3  表示读取公钥失败
			-4  表示签名长度错
			-5  表示签名验证失败
			-99 表示系统锁定失败
			*******************/			
			if($result == 0)
			{
				$verify = true;
			}
		}

		//md5摘要验证方式
		if($pRetEncodeType == '12')
		{
			//明文=订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种+商户证书
			$signature_local = md5($content . $MD5key);

			if($pSignature == $signature_local)
			{
				$verify = true;
			}
		}

		if($verify)
		{
			echo '录入成功！';
			exit();
		}
		else
		{
			echo '签名验证失败！';
			exit();
		}
	}
	else
	{
		echo "录入失败：$pMsg";
		exit();
	}
}
else
{
	//录入成功返回地址 
	$pAuthSuccessUrl = $_POST['pAuthSuccessUrl'];

	//录入失败返回地址 
	$pAuthFailureUrl = $_POST['pAuthFailureUrl'];
?>
<html>
  <head>
    <title>跳转......</title>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
    <form name="sendOrder" id="sendOrder" method="post" action="<?php echo $actionUrl; ?>">
      <input type="hidden" name="pBillNo" value="<?php echo $pBillNo; ?>" />
      <input type="hidden" name="pMerCode" value="<?php echo $pMerCode; ?>" />
      <input type="hidden" name="pCurrency" value="<?php echo $pCurrency; ?>" />
      <input type="hidden" name="pLang" value="<?php echo $pLang; ?>" />
      <input type="hidden" name="pAmount" value="<?php echo $pAmount; ?>" />
      <input type="hidden" name="pDate" value="<?php echo $pDate; ?>" />
      <input type="hidden" name="pAttach" value="<?php echo $pAttach; ?>" />
      <input type="hidden" name="pGateWayType" value="<?php echo $pGateWayType; ?>" />
      <input type="hidden" name="pRetEncodeType" value="<?php echo $pRetEncodeType; ?>" />
      <input type="hidden" name="pOrderEncodeType" value="<?php echo $pOrderEncodeType; ?>" />
      <input type="hidden" name="pSignMD5" value="<?php echo $pSignMD5; ?>" />
      <input type="hidden" name="pAuthority" value="<?php echo $pAuthority; ?>" />
      <input type="hidden" name="pBillEXP" value="<?php echo $pBillEXP; ?>" />
      <input type="hidden" name="pCardInfo" value="<?php echo $pCardInfo; ?>" />
      <input type="hidden" name="pResultType" value="<?php echo $pResultType; ?>" />
      <input type="hidden" name="pReturnUrl" value="<?php echo $pReturnUrl; ?>" />
      <input type="hidden" name="pAuthSuccessUrl" value="<?php echo $pAuthSuccessUrl; ?>" />
      <input type="hidden" name="pAuthFailureUrl" value="<?php echo $pAuthFailureUrl; ?>" />
      <input type="hidden" name="pGoodsInfo" value="<?php echo $pGoodsInfo; ?>" />
    </form>
    <script language="javascript">
      document.getElementById("sendOrder").submit();
    </script>
  </body>
</html>
<?php
}
?>